package com.ms.p2p.interceptor;


import com.ms.common.utils.AppContext;
import com.ms.p2p.entity.system.AdminUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class AdminLoginVerifyInterceptor implements HandlerInterceptor {
	public static final String loginUrl = "/a/login.aspx";
	private static String PRINCIPAL_SESSION_NAME = "adminUser";

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		AdminUser principal = (AdminUser) AppContext.getSessionAttr(PRINCIPAL_SESSION_NAME);
		if (principal != null) {
			return true;
		}
		if (AppContext.isAjax(request)) {
			response.addHeader("loginStatus", "accessDenied");
			response.sendError(403);
			return false;
		}
		if (request.getMethod().equalsIgnoreCase("GET")) {
			String s1 = request.getRequestURL().toString();
			Object oldUrl = request.getAttribute("oldUrl");
			if (oldUrl != null) {
				s1 = oldUrl.toString();
			}
			if (request.getQueryString() != null) {
				s1 = s1 + "?" + request.getQueryString().toString();
			}

			response.sendRedirect(new StringBuffer("/a/login.aspx?")
					.append("redirectUrl").append("=")
					.append(URLEncoder.encode(s1, "UTF-8")).toString());
		} else {
			response.sendRedirect("/a/login.aspx");
		}
		return false;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		clearCache(response);
	}

	/**
	 * 清除缓存
	 */
	private void clearCache(HttpServletResponse response) {
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
	}

}
